package com.lanyeo.liver.util

import android.graphics.Bitmap
import java.io.ByteArrayOutputStream
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
import java.util.concurrent.SynchronousQueue

class UDPClient : Thread() {
    private val imageQueue = SynchronousQueue<Bitmap>()
    override fun run() {
        val socket = DatagramSocket()

        while (true) {
            val image = imageQueue.take()
            val byteBuffer = ByteArrayOutputStream()
            image.compress(Bitmap.CompressFormat.JPEG, 100, byteBuffer)
            val bytes = byteBuffer.toByteArray()
            var offset = 0
            var len = MAX_SEND_SIZE
            while (true) {
                if (bytes.size - offset < MAX_SEND_SIZE) {
                    len = bytes.size - offset
                }
                val data = DatagramPacket(bytes, offset, len, InetAddress.getByName("192.168.3.220"), 8888)
                socket.send(data)
                offset += MAX_SEND_SIZE
                if (len < MAX_SEND_SIZE) {
                    socket.send(DatagramPacket(END, END.size, InetAddress.getByName("192.168.3.220"), 8888))
                    break
                }
            }
        }
    }
    fun put(image: Bitmap) {

    }

    companion object {
        private const val MAX_SEND_SIZE = 1460
        private val END = "1234".encodeToByteArray()
    }
}